import java.util.LinkedList;
import java.util.Queue;

/**
 * 队列实现栈
 */
public class QueueImplementStack {
    Queue<Integer> queue1 = new LinkedList<>();//队列是个接口
    Queue<Integer> queue2 = new LinkedList<>();

    //将元素 x 压入栈顶
    public void push(int x) {
        if (!queue1.isEmpty()) {
            queue1.offer(x);
        } else {
            queue2.offer(x);
        }
    }

    //移除并返回栈顶元素
    public int pop() {
        if (empty()) {
            return -1;
        }
        int size = 0;
        if (!queue1.isEmpty()) {
            size = queue1.size();
            while (size > 1) {
                queue2.offer(queue1.poll());
            }
            return queue1.poll();
        } else {
            size = queue2.size();
            while (size > 1) {
                queue1.offer(queue2.poll());
                size--;
            }
            return queue2.poll();
        }
    }

    //返回栈顶元素
    public int top() {
        if (empty()) {
            return -1;
        }
        int size = 0;
        if (!queue1.isEmpty()) {
            size = queue1.size();
            while (size > 1) {
                queue2.offer(queue1.poll());
                size--;
            }
            int ret = queue1.peek();
            queue2.offer(queue1.poll());
            return ret;
        } else {
            size = queue2.size();
            while (size > 1) {
                queue1.offer(queue2.poll());
                size--;
            }
            int ret = queue2.peek();
            queue1.offer(queue2.poll());
            return ret;
        }
    }

    //如果栈是空的，返回 true ；否则，返回 false
    public boolean empty() {
        if (queue1.isEmpty() && queue2.isEmpty()) {
            return true;
        } else {
            return false;
        }
    }
}

class Test {
    public static void main(String[] args) {
        QueueImplementStack queueImplementStack = new QueueImplementStack();
        queueImplementStack.push(1);
        queueImplementStack.push(2);

        System.out.println(queueImplementStack.top());
        queueImplementStack.pop();
        System.out.println(queueImplementStack.empty());
    }
}
